package com.itheima.handler;

import com.itheima.doman.Result;
import com.itheima.exception.ClazzDeleteException;
import com.itheima.exception.DeptDeleteException;
import com.itheima.exception.ViolationScoreDeleteException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("异常是：", e);
        return Result.error("系统异常，请稍后再试");
    }

    @ExceptionHandler
    public Result handeDuplicateKeyException(RuntimeException e) {
        log.error("异常是：{}", e.getMessage());
        String message = e.getMessage();
        int index = message.indexOf("Duplicate Entry");
        String errorMessage = message.substring(index);
        String[] split = errorMessage.split(" ");
        return Result.error(split[2] + "' 已存在，请重新输入");
    }

        @ExceptionHandler(DeptDeleteException.class)
        public Result DeptDeleteException(DeptDeleteException e) {
            log.error("删除部门异常：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
        @ExceptionHandler(ViolationScoreDeleteException.class)
        public Result ViolationScoreDeleteException(ViolationScoreDeleteException e) {
            log.error("学生违规异常：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
        @ExceptionHandler(ClazzDeleteException.class)
        public Result ClazzDeleteException(ClazzDeleteException e) {
            log.error("删除班级异常：{}", e.getMessage());
            return Result.error(e.getMessage());
        }


}
